package com.atguigu.spzx.product.service.impl;

import com.atguigu.spzx.model.entity.product.Category;
import com.atguigu.spzx.product.mapper.CategoryMapper;
import com.atguigu.spzx.product.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName: CategoryServiceImpl
 * @Package: com.atguigu.spzx.product.service.impl
 * @Description
 * @Author 孤妤
 * @Date: 2023/12/18 11:52
 */
@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    @Transactional(readOnly = true)
    @Cacheable(value = "category" , key = "'all'")
    public List<Category> findAllCategoryTree() {
        // 获取所有分类
        List<Category> categoryList = categoryMapper.selectAllCategoryTree();
        // 获取一级分类
        List<Category> categoryTreeOne = categoryList.stream().filter(category -> category.getParentId() == 0).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(categoryTreeOne)) {
            categoryTreeOne.forEach(categoryOne -> {
                // 获取二级分类
                List<Category> categoryTreeTwo = categoryList.stream().filter(category -> categoryOne.getId().longValue() == category.getParentId()).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(categoryTreeTwo)){
                    categoryOne.setChildren(categoryTreeTwo);
                    categoryTreeTwo.forEach(categoryTwo -> {
                        // 获取三级分类
                        List<Category> categoryTreeThree = categoryList.stream().filter(category -> categoryTwo.getId().longValue() == category.getParentId()).collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(categoryTreeThree)){
                            categoryTwo.setChildren(categoryTreeThree);
                        }
                    });
                }
            });
        }
        return categoryTreeOne;
    }
}
